﻿using BLL.RYGL;
using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using YQFK.Models;

namespace YQFK.api
{
    /// <summary>
    /// 人员管理
    /// </summary>
    public class EmployeeController : ApiController
    {
        private readonly EmployeeBLL _employeeBLL;
        public EmployeeController()
        {
            _employeeBLL = new EmployeeBLL();
        }

        /// <summary>
        /// 人员列表
        /// </summary>
        /// <param name="pageSize">页记录数</param>
        /// <param name="pageIndex">页</param>
        /// <param name="employeeType">人员类型 管理人员/劳务人员</param>
        /// <param name="deptid">单位</param>
        /// <param name="name">人名</param>
        /// <param name="inoutType">进退场 已进场/已退场</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagingModel<EmployeeModel>> Get([FromUri]int pageSize, [FromUri]int pageIndex, [FromUri]string employeeType = null, [FromUri]string deptid = null, [FromUri]string name = null, string inoutType = null)
        {
            var total = 0;
            var data = await _employeeBLL.ListAsync(deptid, name, employeeType, inoutType, pageSize, pageIndex, out total);
            return new PagingModel<EmployeeModel>() { Data = data, Total = total };
        }

        /// <summary>
        /// 人员详情
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<EmployeeModel> Get(Guid id)
        {
            var model = await _employeeBLL.GetAsync(id);
            if (model.EmployeeImage != null) model.EmployeeImage.Url = Url.Link("DefaultApi", new { id = model.EmployeeImage.AttachmentId, controller = "Attachment", action = "Get" });
            if (model.Yqzs != null && model.Yqzs.Attachments != null)
            {
                foreach (var item in model.Yqzs.Attachments)
                {
                    item.Url = Url.Link("DefaultApi", new { id = item.AttachmentId, controller = "Attachment", action = "Get" });
                }
            }
            return model;
        }

        ///// <summary>
        ///// 新增人员
        ///// </summary>
        ///// <param name="model">内容</param>
        ///// <response code="201">新增成功</response>
        ///// <response code="500">验证失败</response>
        //public async Task<IHttpActionResult> Post([FromBody]EmployeeModel model)
        //{
        //    if (!ModelState.IsValid) return BadRequest();

        //    model.EmployeeId = Guid.NewGuid();
        //    await _employeeBLL.CreateAsync(model);
        //    return Created(nameof(Get), model);
        //}

        public async Task<IHttpActionResult> Post()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string filepath = Path.Combine(AppContext.BaseDirectory, "App_Data");
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);

            var provider = new MultipartFormDataStreamProvider(filepath);
            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                var json = provider.FormData["json"];
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<EmployeeModel>(json);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var attachmentModel = new AttachmentModel() { AttachmentId = Guid.NewGuid(), FileName = file.Headers.ContentDisposition.FileName.Trim(new char[] { '"' }), MediaType = file.Headers.ContentType.MediaType };
                    var fileinfo = new FileInfo(file.LocalFileName);
                    using (var fs = fileinfo.OpenRead())
                    {
                        attachmentModel.FileStream = new byte[fs.Length];
                        fs.Read(attachmentModel.FileStream, 0, attachmentModel.FileStream.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    if (file.Headers.ContentDisposition.Name.Trim(new char[] { '"' }) == "EmployeeImage")
                        model.EmployeeImage = attachmentModel;
                    else
                    {
                        if (model.Yqzs.Attachments == null)
                            model.Yqzs.Attachments = new List<AttachmentModel>();

                        model.Yqzs.Attachments.Add(attachmentModel);
                    }

                    attachmentModel.Extension = attachmentModel.FileName.Substring(attachmentModel.FileName.LastIndexOf('.'));
                    File.Delete(file.LocalFileName);
                }

                if (!ModelState.IsValid) return BadRequest(ModelState);

                model.EmployeeId = Guid.NewGuid();
                model.CreateTime = DateTime.Now;
                model.Yqzs.YqzsId = model.EmployeeId;
                foreach (var item in model.Yqzs.Tracks)
                {
                    item.TrackId = Guid.NewGuid();
                }
                await _employeeBLL.CreateAsync(model);
                if (model.EmployeeImage != null)
                {
                    model.EmployeeImage.FileStream = null;
                }

                return Created(nameof(Get), model);
            }
            catch (EmployeeDuplicateException e)
            {
                return BadRequest(e.Message);
            }
            catch (System.Exception e)
            {
                return InternalServerError(e);
            }
        }

        /// <summary>
        /// 编辑人员
        /// </summary>
        /// <param name="model">内容</param>
        /// <response code="200">编辑成功</response>
        /// <response code="500">验证失败</response>
        public async Task<IHttpActionResult> Put()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string filepath = Path.Combine(AppContext.BaseDirectory, "App_Data");
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);

            var provider = new MultipartFormDataStreamProvider(filepath);
            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                var json = provider.FormData["json"];
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<EmployeeModel>(json);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var attachmentModel = new AttachmentModel() { AttachmentId = Guid.NewGuid(), FileName = file.Headers.ContentDisposition.FileName.Trim(new char[] { '"' }), MediaType = file.Headers.ContentType.MediaType };
                    var fileinfo = new FileInfo(file.LocalFileName);
                    using (var fs = fileinfo.OpenRead())
                    {
                        attachmentModel.FileStream = new byte[fs.Length];
                        fs.Read(attachmentModel.FileStream, 0, attachmentModel.FileStream.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    if (file.Headers.ContentDisposition.Name.Trim(new char[] { '"' }) == "EmployeeImage")
                        model.EmployeeImage = attachmentModel;
                    else
                    {
                        if (model.Yqzs.Attachments == null)
                            model.Yqzs.Attachments = new List<AttachmentModel>();

                        model.Yqzs.Attachments.Add(attachmentModel);
                    }

                    attachmentModel.Extension = attachmentModel.FileName.Substring(attachmentModel.FileName.LastIndexOf('.'));
                    File.Delete(file.LocalFileName);
                }

                if (!ModelState.IsValid) return BadRequest(ModelState);

                if (model.Yqzs != null && model.Yqzs.Tracks != null)
                {
                    foreach (var item in model.Yqzs.Tracks)
                    {
                        if (item.TrackId == Guid.Empty)
                            item.TrackId = Guid.NewGuid();
                    }
                }

                await _employeeBLL.UpateAsync(model);
                if (model.EmployeeImage != null)
                {
                    model.EmployeeImage.FileStream = null;
                }

                return Ok();
            }
            catch (EmployeeDuplicateException e)
            {
                return BadRequest(e.Message);
            }
            catch (System.Exception e)
            {
                return InternalServerError(e);
            }


            //if (!ModelState.IsValid) return BadRequest();

            //model.EmployeeId = id;
            //await _employeeBLL.UpateAsync(model);
            //return Ok();
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="id">主键</param>
        /// <response code="200">删除成功</response>
        /// <response code="404">不存在</response>
        public async Task<IHttpActionResult> Delete(Guid id)
        {
            var model = await _employeeBLL.GetAsync(id);
            if (model == null) return NotFound();
            await _employeeBLL.DeleteAsync(id);
            return Ok();
        }
    }
}
